package top.revery.task.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.revery.api.entity.task.BaseTask;
import top.revery.api.entity.task.BaseTaskAppeal;
import top.revery.task.dto.TaskAppealDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/19 14:08
 */
@Service
//@Transactional
public class TaskAppealService {
    @Autowired
    private TaskAppealDto taskAppealDto;

    public Page<BaseTaskAppeal> findPage(int pageNum, int pageSize, Map map) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "appealT");
        Specification<BaseTaskAppeal> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(order));
        return taskAppealDto.findAll(specification, pageRequest);
    }

    private Specification<BaseTaskAppeal> createSpecification(Map map) {
        return new Specification<BaseTaskAppeal>() {
            @Override
            public Predicate toPredicate(Root<BaseTaskAppeal> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }

                if (map.get("userId") != null && !"".equals(map.get("userId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("userId"), map.get("userId")));
                }
                if (map.get("taskId") != null && !"".equals(map.get("taskId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("taskId"), map.get("taskId")));
                }
                if (map.get("status") != null && !"".equals(map.get("status"))) {
                    predicate.getExpressions().add(cb.equal(root.get("status"), map.get("status")));
                }
                return predicate;
            }
        };

    }
}
